package LC;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.com/problems/permutations/description/
 * Given a collection of distinct numbers, return all possible permutations.
 * For example,
 * [1,2,3] have the following permutations:
 * [
 * [1,2,3],
 * [1,3,2],
 * [2,1,3],
 * [2,3,1],
 * [3,1,2],
 * [3,2,1]
 * ]
 */
public class LC_046_Permutations_DFS_Perm {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        List<List<Integer>> res = Solution.permute(a);
        System.out.println(res);
    }

    static class Solution {
        static List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            dfs(res, nums, 0);
            return res;
        }

        private static void dfs(List<List<Integer>> res, int[] nums, int idx) {
            if (idx == nums.length) {
                List<Integer> list = new ArrayList<>();
                for (int num : nums)
                    list.add(num);
                res.add(list);
            } else {
                for (int i = idx; i < nums.length; i++) {
                    swap(nums, i, idx);
                    dfs(res, nums, idx + 1);
                    swap(nums, i, idx);
                }
            }
        }

        private static void swap(int[] nums, int m, int n) {
            if (m == n)
                return;
            nums[m] = nums[m] ^ nums[n];
            nums[n] = nums[m] ^ nums[n];
            nums[m] = nums[m] ^ nums[n];
        }
    }
}
